package com.example.seeksubscribe.Activity;



import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CoordinateConverter;
import com.amap.api.maps2d.CoordinateConverter.CoordType;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.overlay.PoiOverlay;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.Query;
import com.autonavi.amap.mapcore.DPoint;
import com.example.dao.MyApplication;
import com.example.entity.AddressLocation;
import com.example.seeksubscribe.R;
import com.example.seeksubscribe.adapter.AddressLocateAdapter;
import com.example.utils.ToastUtil;
/**
 * 地图查找定位位置
 * @author User
 *
 */
public class AddressLocateActivity extends BaseActivity implements 
OnPoiSearchListener
,AMapLocationListener
,LocationSource
{
	//声明变量
	private MapView mapView;
	private AMap aMap;
	private MarkerOptions markerOption;
	//回退
	private RelativeLayout title_return_rl;
	//查找按钮
	private TextView title_reight_tv;
	//地址输入框
	private EditText find_address_et;
	//手动确定地址按钮
	private TextView address_manual_tv;
	//最后手动的地址
	private String handAddress="";
	//最后定位的地址
	private String locationAddress="";
	//显示地址lv
	private ListView address_lv;
	private ArrayList<String> addarraylist;
	private ProgressDialog progDialog = null;// 搜索时进度条
	private Query query;
	private PoiResult poiResult;
	//-----------------------地图定位--------------------
	private LocationManagerProxy mLocationManagerProxy;
	//坐标对象
	private LatLng l;
	//显示系统小蓝点
	private OnLocationChangedListener mListener;
	//没网的情况下在这里输入地址
	private EditText address_notiw_et;
	//放地址的list
	List<String> addresslist=new ArrayList<String>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(1);
		super.onCreate(savedInstanceState);
		//显示地图
		setContentView(R.layout.activity_address);
		findview();
		mapView.onCreate(savedInstanceState);// 必须要写
		aMap = mapView.getMap();
		dingwei();
		init();
	}
	private void findview() {
		mapView = (MapView) findViewById(R.id.map);
		title_return_rl=(RelativeLayout)findViewById(R.id.title_return_rl);
		title_reight_tv=(TextView)findViewById(R.id.title_reight_tv);
		address_manual_tv=(TextView)findViewById(R.id.address_manual_tv);
		find_address_et=(EditText)findViewById(R.id.find_address_et);
		address_notiw_et=(EditText)findViewById(R.id.address_notiw_et);
		address_lv=(ListView)findViewById(R.id.address_lv);
	}
	private void init() {
		title_return_rl.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String addressString=address_notiw_et.getText().toString();
				handAddress=addressString;
				Intent i = new Intent();
				Bundle b = new Bundle();
				if (locationAddress.length()>0&&handAddress.length()>0) {
					b.putString("address", locationAddress+"("+handAddress+")");
				}else if (locationAddress.length()<=0&&handAddress.length()>0) {
					b.putString("address", handAddress);
				}else if (locationAddress.length()>0&&handAddress.length()<=0) {
					b.putString("address", locationAddress);
				}else{
					b.putString("address", "");
				}
				i.putExtra("address", b);
				setResult(100, i);
				finish();
			}
		});
		title_reight_tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String addressString=find_address_et.getText().toString();
				if (addressString.length()<=0||addressString==null) {
					toast("请输入地址查询", AddressLocateActivity.this);
				}else {
					//再次定位
					dingwei();
					if (MyApplication.addl!=null&&MyApplication.addl.getCode().length()>0) {
						showProgressDialog();// 显示进度框
						query = new PoiSearch.Query(addressString, "", MyApplication.addl.getCode());
						// keyWord表示搜索字符串，
						//第二个参数表示POI搜索类型，二者选填其一，
						//POI搜索类型共分为以下20种：汽车服务|汽车销售|
						//汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|
						//住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|
						//金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
						//cityCode表示POI搜索区域的编码，是必须设置参数
						query.setPageSize(10);// 设置每页最多返回多少条poiitem
						query.setPageNum(1);//设置查询页码
						PoiSearch poiSearch = new PoiSearch(AddressLocateActivity.this,query);//初始化poiSearch对象
						poiSearch.setOnPoiSearchListener(AddressLocateActivity.this);//设置回调数据的监听器
						poiSearch.searchPOIAsyn();//开始搜索
					}else {
						toast("定位失败，请检查网络连接，或手动输入详细地址信息", AddressLocateActivity.this);
					}
				}
			}
		});
		address_manual_tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String addressString=address_notiw_et.getText().toString();
				if (addressString.length()<=0||addressString==null) {
					toast("请输入输入详细地址信息", AddressLocateActivity.this);
				}else {
					handAddress=addressString;
					Intent i = new Intent();
					Bundle b = new Bundle();
					if (locationAddress.length()>0&&handAddress.length()>0) {
						b.putString("address", locationAddress+"("+handAddress+")");
					}else if (locationAddress.length()<=0&&handAddress.length()>0) {
						b.putString("address", handAddress);
					}else if (locationAddress.length()>0&&handAddress.length()<=0) {
						b.putString("address", locationAddress);
					}else{
						b.putString("address", "");
					}
					i.putExtra("address", b);
					setResult(100, i);
					finish();
				}
			}
		});
		address_lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String address=addresslist.get(position);
				if (address.length()>0) {
					Intent i = new Intent();
					Bundle b = new Bundle();
					b.putString("address", address);
					i.putExtra("address", b);
					setResult(100, i);
					finish();
				}
			}
		});
	}
	//搜索后回调
	public void onPoiSearched(PoiResult result, int rCode) {
		//可以在回调中解析result，获取POI信息
		//result.getPois()可以获取到PoiItem列表，Poi详细信息可参考PoiItem类
		//若当前城市查询不到所需Poi信息，可以通过result.getSearchSuggestionCitys()获取当前Poi搜索的建议城市
		//如果搜索关键字明显为误输入，则可通过result.getSearchSuggestionKeywords()方法得到搜索关键词建议
		//返回结果成功或者失败的响应码。0为成功，其他为失败（详细信息参见网站开发指南-错误码对照表）

		dissmissProgressDialog();// 隐藏对话框
		if (rCode == 0) {
			if (result != null && result.getQuery() != null) {// 搜索poi的结果
				if (result.getQuery().equals(query)) {// 是否是同一条
					poiResult = result;
					// 取得搜索到的poiitems有多少页
					List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
					addresslist.clear();
					for (int i = 0; i < poiItems.size(); i++) {
						String citynameString=poiItems.get(i).getCityName();
						String nubmerString=poiItems.get(i).getSnippet();
						//设置list显示地址
						addresslist.add(citynameString+nubmerString);
					}
					AddressLocateAdapter adapter = new AddressLocateAdapter(AddressLocateActivity.this, addresslist);
					address_lv.setAdapter(adapter);
					
					
					if (poiItems != null && poiItems.size() > 0) {
						aMap.clear();// 清理之前的图标
						PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
						poiOverlay.removeFromMap();
						poiOverlay.addToMap();
						poiOverlay.zoomToSpan();
					}else {
						toast("对不起，没有搜索到相关数据！请手动输入详细地址信息",AddressLocateActivity.this);
					}
				}
			} else {
				toast("对不起，没有搜索到相关数据！请手动输入详细地址信息",AddressLocateActivity.this);
			}
		} else if (rCode == 27) {
			toast("搜索失败,请检查网络连接，或手动输入详细地址信息", AddressLocateActivity.this);
		} else if (rCode == 32) {
			toast("搜索失败，key验证无效！请手动输入详细地址信息", AddressLocateActivity.this);
		} else {
			toast("搜索失败，请稍后重试!请手动输入详细地址信息", AddressLocateActivity.this);
		}
	}

	/**
	 * 显示进度框
	 */
	private void showProgressDialog() {
		if (progDialog == null)
			progDialog = new ProgressDialog(this);
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setIndeterminate(false);
		progDialog.setCancelable(false);
		progDialog.setMessage("正在搜索...");
		progDialog.show();
	}

	/**
	 * 隐藏进度框
	 */
	private void dissmissProgressDialog() {
		if (progDialog != null) {
			progDialog.dismiss();
		}
	}
	





	//-------------------地图定位---------------------------
	/**
	 * 初始化定位
	 */
	private void dingwei() {      
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
	}
	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mLocationManagerProxy == null) {
			mLocationManagerProxy = LocationManagerProxy.getInstance(this);
			//此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
			//注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
			//在定位结束后，在合适的生命周期调用destroy()方法     
			//其中如果间隔时间为-1，则定位只定一次
			mLocationManagerProxy.requestLocationData(
					LocationProviderProxy.AMapNetwork, -1, 15, AddressLocateActivity.this);
			showWaitDialog();
		}

	}
	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}
	/**
	 * 定位成功后回调函数
	 */
	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		if(amapLocation != null && amapLocation.getAMapException().getErrorCode() == 0){
			aMap.clear();// 清理之前的图标 
			//获取位置信息
			MyApplication.addl=new AddressLocation();
			//纬度
			double geoLat = amapLocation.getLatitude();
			MyApplication.addl.setGeoLat(geoLat);
			System.out.println("定位纬度==》》"+MyApplication.addl.getGeoLat());
			//经度
			double geoLng = amapLocation.getLongitude();   
			MyApplication.addl.setGeoLng(geoLng);
			System.out.println("定位经度==》》"+MyApplication.addl.getGeoLng());
			//获取定位速度
			float speed = amapLocation.getSpeed();   
			MyApplication.addl.setSpeed(speed);
			System.out.println("获取定位速度==》》"+MyApplication.addl.getSpeed());
			//方向
			float bearing = amapLocation.getBearing();
			MyApplication.addl.setBearing(bearing);
			System.out.println("定位方向==》》"+bearing);
			//省名称
			String province = amapLocation.getProvince();  
			MyApplication.addl.setProvince(province);
			System.out.println("省份名称==》》"+province);
			//城市名称
			String city = amapLocation.getCity();   
			MyApplication.addl.setCity(city);
			System.out.println("城市名称==》》"+city);
			//城市编码
			String code = amapLocation.getCityCode();
			MyApplication.addl.setCode(code);
			System.out.println("城市编码==》》"+code);
			//区（县）名称
			String district = amapLocation.getDistrict(); 
			MyApplication.addl.setDistrict(district);
			System.out.println("区（县）名称==》》"+district);
			//区域编码
			String adcode = amapLocation.getAdCode(); 
			MyApplication.addl.setAdcode(adcode);
			System.out.println("区域编码==》》"+adcode);
			//街道和门牌信息
			String street = amapLocation.getStreet(); 
			MyApplication.addl.setStreet(street);
			System.out.println("街道和门牌信息==》》"+street);
			//详细地址
			String address = amapLocation.getAddress(); 
			MyApplication.addl.setAddress(address);
			locationAddress=address;
			System.out.println("详细地址==》》"+MyApplication.addl.getAddress());
			//描述信息
			Bundle extras = amapLocation.getExtras();   
			MyApplication.addl.setExtras(extras);
			System.out.println("描述信息==》》"+extras.toString());

			//设置list显示地址
			addresslist.clear();
			addresslist.add(locationAddress);
			AddressLocateAdapter adapter = new AddressLocateAdapter(AddressLocateActivity.this, addresslist);
			address_lv.setAdapter(adapter);
			
			
			//声明一个动画帧集合。//小蓝点上显示字
			ArrayList giflist = new ArrayList();
			l=new LatLng(geoLat, geoLng);
			//添加每一帧图片。
			giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.end));
			//设置远小近大效果,设置刷新一次图片资源的周期。
			aMap.addMarker(
					new MarkerOptions()
					.anchor(0.5f, 0.5f)
					.position(l)
					.title(city)
					.snippet(address)
					.icons(giflist)
					.draggable(true)
					.period(50)).showInfoWindow();


			//显示地图小蓝点
			mListener.onLocationChanged(amapLocation);// 显示系统小蓝点

			//----------------------在地图上显示结束------把地址显示在listview上-----------------------

		}else {
			ToastUtil.makeText(AddressLocateActivity.this, "定位失败", 0);
		}
		dismissDialog();
	}
	/**
	 * 停止定位
	 */
	public void deactivate() {
		if (mLocationManagerProxy != null) {
			mLocationManagerProxy.removeUpdates(this);
			mLocationManagerProxy.destroy();
		}
		mLocationManagerProxy = null;
	}
}
